package controllers;

import models.LoginUsuario;
import models.dao.DAOLoginUsuario;
import play.data.Form;
import play.mvc.*;
import views.html.*;


public class CtrlLogin extends Controller{
	
	//Form do login
	private static Form<LoginUsuario> formLogin = new Form<LoginUsuario>(LoginUsuario.class);
	
	//Pagina de Login
	public static Result login(){
		return ok(views.html.login.login.render(formLogin, ""));
	}
	
	//Metodo de autenticação de usuario
	public static Result autenticar(){
		Form<LoginUsuario> form = formLogin.bindFromRequest();
		LoginUsuario l = form.get();
		
		//teste
		System.out.println(l.email + " - " + l.senha);
		
		DAOLoginUsuario dao = new DAOLoginUsuario();
		
		if (dao.login(l)){
			session("email", l.email);
			session("perfil", dao.perfil(l).perfil);
    		return redirect(routes.CtrlLogin.inicio());
			
    	}else {
    		return ok(views.html.login.login.render(form, "Email ou senha inválida!"));
		}
	}
	
	//Pagina Inicial
	@Security.Authenticated(Seguranca.class)
	public static Result inicio(){
		return ok(inicio.render());
	}
	
	//Metodo de logout do sistema
	@Security.Authenticated(Seguranca.class)
	public static Result logout(){
		session().clear();
    	return redirect(routes.CtrlLogin.login());
		
	}
}
